import { DeleteOutlined, UploadOutlined } from '@ant-design/icons'
import { useSessionStorage } from '@hooks/useSessionStorage'
import { API_UPLOAD_URL } from '@services/baseApi'
import { Button, Upload } from 'antd'
import React, { useMemo } from 'react'

export const FormUpload = ({
  filelist,
  btnText = '上传附件',
  onBefore,
  onChange,
  extra,
  children,
}) => {
  console.log('%c Line:7 🍪 filelist', 'color:#ed9ec7', filelist)
  const [token] = useSessionStorage('token')

  const uploadProps = useMemo(
    () => ({
      action: '/api' + API_UPLOAD_URL,
      headers: {
        authorization: token ? `Bearer ${token}` : undefined,
      },
      defaultFileList: filelist.map((t) => ({ ...t, uid: t.url })),
      beforeUpload: (file) => onBefore?.(file) || true,
      onChange({ file, fileList }) {
        if (file.response && file.status === 'done') {
          console.log('upload file =>', 'color:#52c41a', file)
          onChange((prev) => [...prev, file.response])
        }

        if (file.status === 'removed') {
          console.log('romoved file =>', 'color:#ea7e5c', file)
          const url = file.url || file.response.url
          onChange((prev) => prev.filter((item) => item.url !== url))
        }

        if (file.status === 'error') {
          console.error(file, fileList)
        }
      },
      showUploadList: {
        extra: (file) => {
          const curfile = file.response ? file.response : file
          return (
            <>
              <span style={{ color: '#cccccc', marginLeft: '8px' }}>
                ({file.response?.size || file.size})
              </span>
              {extra &&
                React.cloneElement(extra, {
                  onClick: (e) => extra.props.onClick(e, curfile),
                  style: {
                    color: extra.props.checkUrl === curfile.url ? '#43D45B' : '',
                  },
                })}
            </>
          )
        },
        showRemoveIcon: true,
        removeIcon: <DeleteOutlined />,
      },
      listType: 'picture', // 添加列表类型
    }),
    [filelist, token, onChange, onBefore, extra],
  )

  return (
    <Upload {...uploadProps}>
      <Button icon={<UploadOutlined />}>{btnText}</Button>
      {children}
    </Upload>
  )
}
